<route lang="json5">
{
  style: {
    navigationBarTitleText: '纪念日'
  }
}
</route>

<script lang="ts" setup>
import type { Anniversary } from '@/types/couple'
import dayjs from 'dayjs'
import { ref, computed, onMounted } from 'vue'
import { useToast } from 'wot-design-uni'
import { useSupabaseCoupleStore } from '@/store/supabaseCouple'

defineOptions({
  name: 'Anniversary',
})

const coupleStore = useSupabaseCoupleStore()
const { success: showSuccess } = useToast()

const showAddDialog = ref(false)
const showDatePicker = ref(false)
const newAnniversary = ref<Partial<Anniversary>>({
  title: '',
  date: dayjs().format('YYYY-MM-DD'),
  type: 'custom',
  description: '',
  isRecurring: true,
  reminderDays: 3,
})

// 用于日期选择器的临时变量（时间戳）
const tempDate = ref(Date.now())

const anniversaryTypes = [
  { label: '恋爱纪念日', value: 'love' },
  { label: '生日', value: 'birthday' },
  { label: '结婚纪念日', value: 'wedding' },
  { label: '自定义', value: 'custom' },
]

// 按月份分组的纪念日
const groupedAnniversaries = computed(() => {
  const groups: { [key: string]: Anniversary[] } = {}

  coupleStore.anniversaries.forEach((anniversary) => {
    const month = dayjs(anniversary.date).format('YYYY年MM月')
    if (!groups[month]) {
      groups[month] = []
    }
    groups[month].push(anniversary)
  })

  // 按月份排序
  const sortedGroups = Object.keys(groups)
    .sort()
    .reduce((acc, key) => {
      acc[key] = groups[key].sort((a, b) =>
        dayjs(a.date).date() - dayjs(b.date).date(),
      )
      return acc
    }, {} as { [key: string]: Anniversary[] })

  return sortedGroups
})

// 获取纪念日类型标签
const getTypeLabel = (type: string) => {
  const typeItem = anniversaryTypes.find(t => t.value === type)
  return typeItem?.label || '自定义'
}

// 获取纪念日颜色
const getTypeColor = (type: string) => {
  const colors = {
    love: '#ff6b9d',
    birthday: '#4ecdc4',
    wedding: '#45b7d1',
    custom: '#96ceb4',
  }
  return colors[type as keyof typeof colors] || '#96ceb4'
}

// 计算距离天数
const getDaysUntil = (date: string) => {
  const anniversaryDate = dayjs(date)
  const today = dayjs()
  const thisYear = today.year()

  let nextDate = anniversaryDate.year(thisYear)
  if (nextDate.isBefore(today, 'day')) {
    nextDate = nextDate.year(thisYear + 1)
  }

  const days = nextDate.diff(today, 'day')

  if (days === 0)
    return '今天'
  if (days === 1)
    return '明天'
  return `${days}天后`
}

// 添加纪念日
const handleAddAnniversary = () => {
  if (!newAnniversary.value.title || !newAnniversary.value.date) {
    return
  }

  coupleStore.addAnniversary(newAnniversary.value as Omit<Anniversary, 'id' | 'createdAt'>)

  // 重置表单
  newAnniversary.value = {
    title: '',
    date: '',
    type: 'custom',
    description: '',
    isRecurring: true,
    reminderDays: 3,
  }

  showAddDialog.value = false
  showSuccess('纪念日添加成功')
}

// 取消添加
const handleCancel = () => {
  showAddDialog.value = false
  newAnniversary.value = {
    title: '',
    date: '',
    type: 'custom',
    description: '',
    isRecurring: true,
    reminderDays: 3,
  }
}

// 编辑/删除
const showEditDialog = ref(false)
const editingId = ref<string | null>(null)
const editAnniversary = ref<Partial<Anniversary>>({})

function beginEditAnniversary(anniversary: Anniversary) {
  editingId.value = anniversary.id
  editAnniversary.value = { ...anniversary }
  tempDate.value = dayjs(anniversary.date).valueOf()
  showEditDialog.value = true
}

function submitEditAnniversary() {
  if (!editingId.value)
    return
  coupleStore.updateAnniversary(editingId.value, editAnniversary.value)
  showEditDialog.value = false
  editingId.value = null
  showSuccess('纪念日已更新')
}

function confirmRemoveAnniversary(anniversary: Anniversary) {
  uni.showModal({
    title: '删除确认',
    content: `确定删除"${anniversary.title}"吗？`,
    success: ({ confirm }) => {
      if (confirm) {
        coupleStore.removeAnniversary(anniversary.id)
        showSuccess('已删除')
      }
    },
  })
}

function openAnniversaryActions(anniversary: Anniversary) {
  uni.showActionSheet({
    itemList: ['编辑', '删除', '取消'],
    success: (res) => {
      if (res.tapIndex === 0)
        beginEditAnniversary(anniversary)
      else if (res.tapIndex === 1)
        confirmRemoveAnniversary(anniversary)
    },
  })
}

const handleDateConfirm = () => {
  const val = dayjs(tempDate.value).format('YYYY-MM-DD')
  if (showEditDialog.value) {
    editAnniversary.value.date = val
  }
  else {
    newAnniversary.value.date = val
  }
  showDatePicker.value = false
}

onMounted(() => {
  coupleStore.initProfile()
})
</script>

<template>
  <view class="anniversary-container">
    <!-- 添加按钮 -->
    <view class="add-btn-container">
      <wd-button
        type="primary"
        custom-class="add-btn"
        @click="showAddDialog = true"
      >
        <wd-icon name="add" size="16px" />
        添加纪念日
      </wd-button>
    </view>

    <!-- 纪念日列表 -->
    <view class="anniversary-list">
      <view
        v-for="(anniversaries, month) in groupedAnniversaries"
        :key="month"
        class="month-group"
      >
        <view class="month-title">
          {{ month }}
        </view>
        <view class="anniversary-items">
          <view
            v-for="anniversary in anniversaries"
            :key="anniversary.id"
            class="anniversary-item"
          >
            <view
              class="type-indicator bg-[#ff69b4]"
            />
            <view class="anniversary-content">
              <view class="anniversary-header">
                <view class="anniversary-title">
                  {{ anniversary.title }}
                </view>
                <view class="anniversary-date">
                  {{ dayjs(anniversary.date).format('MM月DD日') }}
                </view>
                <view class="anniversary-actions">
                  <wd-button size="small" plain @click="openAnniversaryActions(anniversary)">
                    更多
                  </wd-button>
                </view>
              </view>
              <view class="anniversary-meta">
                <view
                  class="text-xs text-[#ff69b4]"
                >
                  {{ getTypeLabel(anniversary.type) }}
                </view>
                <view class="days-until">
                  {{ getDaysUntil(anniversary.date) }}
                </view>
              </view>
              <view v-if="anniversary.description" class="anniversary-desc">
                {{ anniversary.description }}
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view v-if="coupleStore.anniversaries.length === 0" class="empty-state">
      <wd-icon name="calendar" size="64px" color="#ccc" />
      <text class="empty-text">还没有纪念日，快去添加一个吧！</text>
    </view>

    <!-- 添加纪念日弹窗 -->
    <wd-popup
      v-model="showAddDialog"
      position="bottom"
      :safe-area-inset-bottom="true"
    >
      <view class="add-dialog">
        <view class="dialog-header">
          <view class="dialog-title">
            添加纪念日
          </view>
          <wd-icon name="close" @click="handleCancel" />
        </view>

        <view class="dialog-content">
          <wd-cell-group>
            <wd-input
              v-model="newAnniversary.title"
              label="标题"
              placeholder="请输入纪念日标题"
              required
            />
            <wd-cell title="日期" :value="newAnniversary.date || '请选择日期'" is-link @click="showDatePicker = true; tempDate = newAnniversary.date ? dayjs(newAnniversary.date).valueOf() : Date.now()" />
            <wd-picker
              v-model="newAnniversary.type"
              label="类型"
              :columns="anniversaryTypes"
            />
            <wd-input
              v-model="newAnniversary.description"
              label="描述"
              placeholder="添加一些描述（可选）"
            />
          </wd-cell-group>
        </view>

        <view class="dialog-actions">
          <wd-button @click="handleCancel">
            取消
          </wd-button>
          <wd-button type="primary" @click="handleAddAnniversary">
            确定
          </wd-button>
        </view>
      </view>
    </wd-popup>

    <!-- 编辑纪念日弹窗 -->
    <wd-popup v-model="showEditDialog" position="bottom" :safe-area-inset-bottom="true">
      <view class="add-dialog">
        <view class="dialog-header">
          <view class="dialog-title">
            编辑纪念日
          </view>
          <wd-icon name="close" @click="showEditDialog = false" />
        </view>

        <view class="dialog-content">
          <wd-cell-group>
            <wd-input
              v-model="editAnniversary.title"
              label="标题"
              placeholder="请输入纪念日标题"
              required
            />
            <wd-cell title="日期" :value="editAnniversary.date || '请选择日期'" is-link @click="showDatePicker = true; tempDate = editAnniversary.date ? dayjs(editAnniversary.date).valueOf() : Date.now()" />
            <wd-picker
              v-model="editAnniversary.type"
              label="类型"
              :columns="anniversaryTypes"
            />
            <wd-input
              v-model="editAnniversary.description"
              label="描述"
              placeholder="添加一些描述（可选）"
            />
          </wd-cell-group>
        </view>

        <view class="dialog-actions">
          <wd-button @click="showEditDialog = false">
            取消
          </wd-button>
          <wd-button type="primary" @click="submitEditAnniversary">
            保存
          </wd-button>
        </view>
      </view>
    </wd-popup>

    <!-- 日期选择器 -->
    <wd-popup v-model="showDatePicker" position="bottom">
      <wd-datetime-picker-view
        v-model="tempDate"
        type="date"
        @change="handleDateConfirm"
      />
      <view class="picker-actions">
        <wd-button @click="showDatePicker = false">
          取消
        </wd-button>
        <wd-button type="primary" @click="handleDateConfirm">
          确定
        </wd-button>
      </view>
    </wd-popup>

    <wd-toast />
  </view>
</template>

<style lang="scss" scoped>
.anniversary-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #ffb6c1 0%, #ffc0cb 50%, #ffb6c1 100%);
  padding-bottom: 100px;
  position: relative;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-image:
      radial-gradient(circle at 25% 25%, rgba(255, 182, 193, 0.3) 0%, transparent 50%),
      radial-gradient(circle at 75% 75%, rgba(255, 192, 203, 0.3) 0%, transparent 50%);
    pointer-events: none;
  }
}

.add-btn-container {
  padding: 16px;
  background-color: #fff;
  border-bottom: 1px solid #eee;

  .add-btn {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
  }
}

.anniversary-list {
  padding: 0 16px;
}

.month-group {
  margin-bottom: 24px;

  .month-title {
    font-size: 18px;
    font-weight: 600;
    color: #333;
    margin-bottom: 12px;
    padding-left: 8px;
  }
}

.anniversary-items {
  .anniversary-item {
    display: flex;
    background: white;
    border-radius: 12px;
    padding: 16px;
    margin-bottom: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    .type-indicator {
      width: 4px;
      border-radius: 2px;
      margin-right: 12px;
    }

    .anniversary-content {
      flex: 1;

      .anniversary-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;

        .anniversary-title {
          font-size: 16px;
          font-weight: 600;
          color: #333;
        }

        .anniversary-date {
          font-size: 14px;
          color: #666;
        }
      }

      .anniversary-meta {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;

        .days-until {
          font-size: 12px;
          color: #ff69b4;
          font-weight: 600;
          text-shadow: 0 1px 2px rgba(255, 105, 180, 0.3);
        }
      }

      .anniversary-desc {
        font-size: 14px;
        color: #666;
        line-height: 1.4;
      }
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;

  .empty-text {
    margin-top: 16px;
    font-size: 14px;
    color: #999;
  }
}

.add-dialog {
  background: white;
  border-radius: 16px 16px 0 0;
  max-height: 80vh;

  .dialog-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    border-bottom: 1px solid #eee;

    .dialog-title {
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }
  }

  .dialog-content {
    padding: 20px;
    max-height: 50vh;
    overflow-y: auto;
  }

  .dialog-actions {
    display: flex;
    gap: 12px;
    padding: 20px;
    border-top: 1px solid #eee;
  }
}

.picker-actions {
  display: flex;
  gap: 12px;
  padding: 20px;
  background: white;
  border-top: 1px solid #eee;
}
</style>
